package cn.com.bluemoon.daps.common.datascope.aop;

import cn.com.bluemoon.daps.common.datascope.AuthRole;
import cn.com.bluemoon.daps.common.domain.UserInfoHolder;
import cn.com.bluemoon.daps.common.exception.DapException;
import cn.com.bluemoon.daps.common.toolkit.BmAssetUtils;
import cn.hutool.extra.servlet.ServletUtil;
import org.aspectj.lang.ProceedingJoinPoint;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * 拓展业务自定义角色权限认证
 *
 * @author Jarod.Kong
 */
public interface AuthAccessService {
    /**
     * 附加认证业务拓展方法
     * 放行，反之，抛异常{@link cn.com.bluemoon.daps.common.exception.DapThrowException}
     *
     * @param hasRoleAuth 用户是否有访问该角色权限 true有，false无
     */
    public void checkAuth(UserInfoHolder.UserInfo userInfo,
                          AuthRole authRole,
                          boolean hasRoleAuth,
                          ProceedingJoinPoint aspectPoint,
                          HttpServletRequest servletRequest) throws DapException;

    /**
     * 获取请求入参map
     */
    default Map<String, Object> getRequestParamMap(HttpServletRequest servletRequest) {
        if (servletRequest != null) {
            Map<String, String[]> paramMap = ServletUtil.getParams(servletRequest);
            Map<String, Object> context = new HashMap<>();
            paramMap.forEach(context::put);
            return context;
        }
        return Collections.emptyMap();
    }

    @SuppressWarnings("unchecked")
    default <T> T pjpArgCastTo(Object arg, Class<T> clz) {
        if (arg == null) {
            return null;
        }
        if (clz != null) {
            return clz.cast(arg);
        }
        return (T) arg;
    }

    default String toServletRequestMethod(HttpServletRequest servletRequest) {
        return  servletRequest != null? servletRequest.getMethod(): null;
    }

    default void assertHadRoleAuth(boolean hasRoleAuth, String errorMsg) {
        BmAssetUtils.isTrue(hasRoleAuth, () -> new DapException("权限控制:" + errorMsg));
    }
}
